﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Threading.Tasks;

namespace WebAPIWebSockets.Controllers
{
    public class WebSocketController : ControllerBase
    {
        [Route("/wsTest")]
        public async Task Get()
        {
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
                await WebSocketsHelper.Echo(webSocket);
            }
            else
            {
                HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
            }
        }

        private static List<WebSocket> _sockets = new List<WebSocket>();  // 存储当前所有连接的静态列表
        [Route("/ChatRoom")]
        public async Task ChatRoom()
        {
            try
            {
                if (HttpContext.WebSockets.IsWebSocketRequest)
                {
                    using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
                    await WebSocketsHelper.ChatRoom(webSocket);
                }
                else
                {
                    HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
                }
            }
            catch(Exception ex) 
            {
                string message = ex.Message;
            }
        }
    }
}
